<script setup lang="ts">
import {
  NIcon,
  NButton,
  NGrid,
  NGi,
  NProgress,
  NInput,
  NForm,
  NFormItem,
  NDatePicker,
  NSelect,
  NTreeSelect,
  useMessage,
  NTooltip,
  NEllipsis,
  NSpin,
  type FormInst,
  type SelectOption
} from 'naive-ui'
import { h, type VNode, ref, onMounted, reactive, watch } from 'vue'
import BasicCount from './components/BasicCount/BasicCount.vue'
import GearPie from './components/Echarts/GearPie.vue'
import GearPieL from './components/Echarts/GearPieL.vue'
import { Search, Sync } from '@vicons/ionicons5'
import { sendRequest } from '@/utils/api'
const message = useMessage()
onMounted(() => {
  getCollectorOptions()
  getTreeSelect()
  codeFn('A30', collectFactionList) //征集方式A30

  getCollectWay({}, true)
  getCollectorDonate()
  getCollectCategory()
  getCollectSecondCategory()
})

const banbenList = ref()
const collectFactionList: any = ref()
const collectorOptions = ref([])
/**
 * 格式化日期范围
 */
const formatDate = (e: Array<string>) => {
  formValue.value.startDate = e ? e[0] : ''
  formValue.value.endDate = e ? e[1] : ''
}
/**
 * 获取征集方式列表
 * @param code
 */
const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
/**
 * 获取版本类型树
 */
const getTreeSelect = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listTreeAll',
    override: {
      params: {
        statusCode: 'A4901'
      }
    }
  })
  if (error) return message.error(error.message)
  banbenList.value = res.data
}
/**
 * 获取藏家
 */
const getCollectorOptions = async () => {
  const [error, res] = await sendRequest({
    module: 'dataInsight',
    api: 'listDataViewCollectorOptions'
  })
  if (error) return message.error(error.message)
  collectorOptions.value = res.data
}

// 征集统计图表数据
const colCount = ref(0)
const colGearPieDataAll = reactive({
  data: []
})
// 筛选征集统计图表数据
const colCountFilter = ref(0)
const colGearPieDataFilter = reactive({
  data: []
})
/**
 * 获取征集方式统计
 */
const getCollectWay = async (params: any = {}, isAll: boolean = false) => {
  const [error, res] = await sendRequest({
    module: 'dataInsight',
    api: 'getCollectWay',
    override: {
      params
    }
  })
  if (error) return message.error(error.message)
  let tempArr = res.data.collectWayList.map((item: { name: any; num: any; code: any }) => {
    return {
      name: item.name,
      value: item.num
      // code: item.code
    }
  })
  let count = Number(res.data.collectTotalNum)
  if (isAll) {
    colGearPieDataAll.data = tempArr
    colCount.value = count
  }
  colGearPieDataFilter.data = tempArr
  colCountFilter.value = count
}

/**
 * 渲染选择项tooltip显示
 */
const renderOption = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
)

// 藏家捐赠统计
interface collectorDonateItem {
  name: string
  num: string
}
const collectorDonatePersonal = ref<Array<collectorDonateItem>>([])
const collectorDonateEnterprise = ref<Array<collectorDonateItem>>([])
/**
 * 获取藏家统计数据
 */
const getCollectorDonate = async (params: any = {}) => {
  const [error, res] = await sendRequest({
    module: 'dataInsight',
    api: 'getCollectorDonate',
    override: {
      params
    }
  })
  if (error) return message.error(error.message)

  collectorDonatePersonal.value = res.data.personalList.slice(0, 10)
  collectorDonateEnterprise.value = res.data.organizationList.slice(0, 10)
}

// 征集品一级类型分析
interface collectCategoryListItem {
  category: string
  categoryCode: string
  num: string
}
const collectCategory = reactive({
  data: []
})
const showFirst = ref(false)
/**
 * 获取征集品一级类型数据
 */
const getCollectCategory = async (params: any = {}) => {
  showFirst.value = false
  const [error, res] = await sendRequest({
    module: 'dataInsight',
    api: 'getCollectCategory',
    override: {
      params
    }
  })
  if (error) return message.error(error.message)
  let tempArr = res.data.collectCategoryList.map(
    (item: { category: any; num: any; categoryCode: any }) => {
      return {
        name: item.category,
        value: item.num
        // code: item.categoryCode
      }
    }
  )
  console.log(res)
  collectCategory.data = tempArr
  showFirst.value = true
}

// 征集品二级类型分析
const collectSecondCategory = reactive({
  data: []
})
const showSecond = ref(false)
const collectGategoryTopL = ref<Array<collectCategoryListItem>>([])
const collectGategoryTopR = ref<Array<collectCategoryListItem>>([])
const latestRequestRef = reactive({
  current: 0
})
/**
 * 获取征集品二级类型数据
 */
const getCollectSecondCategory = async (params: any = {}) => {
  showSecond.value = false
  const currentRequest = Date.now() // 加一个时间戳
  latestRequestRef.current = currentRequest // 保存时间戳到最后一次被点击
  const [error, res] = await sendRequest({
    module: 'dataInsight',
    api: 'getCollectSecondCategory',
    override: {
      params
    }
  })
  if (error) return message.error(error.message)
  if (latestRequestRef.current == currentRequest) {
    let collectCategoryList = res.data.collectCategoryList
    let tempArr = collectCategoryList.map(
      (item: { category: any; num: any; categoryCode: any }) => {
        return {
          name: item.category,
          value: item.num
          // code: item.categoryCode
        }
      }
    )
    console.log(res)
    collectSecondCategory.data = tempArr
    collectGategoryTopL.value = collectCategoryList.slice(0, 10)
    collectGategoryTopR.value = collectCategoryList.slice(10, 20)
    showSecond.value = true
  }
}
const onChangeSecondCategory = (name: string) => {
  let itemTypeCode = ''
  console.log('banbenList.value: ', banbenList.value)
  banbenList.value.forEach((item: any) => {
    if (item.classificationName == name) itemTypeCode = item.classificationCode
  })
  let params = JSON.parse(JSON.stringify(cloneParams.value))
  delete params.dateRange
  params.itemTypeCode = itemTypeCode
  getCollectSecondCategory(params)
}

const cloneParams = ref({})
const formRef = ref<FormInst | null>(null)
const rules = ref({
  dateRange: {
    required: false,
    message: '请选择时间范围',
    trigger: 'change'
  },
  itemTypeCode: {
    required: false,
    message: '请选择版本类型',
    trigger: ['change', 'blur']
  }
})
const formValue = ref({
  startDate: '',
  endDate: '',
  dateRange: null,
  solicitMethodCode: null,
  itemTypeCode: null,
  collectorId: null,
  receiver: null
})
const size = ref<'small' | 'medium' | 'large'>('small')
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    console.log('formValue:', formValue.value)
    let params = JSON.parse(JSON.stringify(formValue.value))
    delete params.dateRange
    console.log('params: ', params)
    freshPieDataFilter.value = false
    getCollectWay(params)
    getCollectorDonate(params)
    getCollectCategory(params)
    getCollectSecondCategory(params)
    // 保存查询过的参数
    cloneParams.value = params
  })
}
const handleRestoreValidationClick = () => {
  formRef.value?.restoreValidation()
  formValue.value.dateRange = null
  formValue.value.startDate = ''
  formValue.value.endDate = ''
  formValue.value.solicitMethodCode = null
  formValue.value.itemTypeCode = null
  formValue.value.collectorId = null
  formValue.value.receiver = null
  // Object.keys(formValue.value).forEach((key) => {
  //   formValue.value[key] = null
  // })
}

const freshPieDataAll = ref(false)
watch(
  () => colGearPieDataAll.data,
  () => {
    freshPieDataAll.value = true
  }
)

const freshPieDataFilter = ref(false)
watch(
  () => colGearPieDataFilter.data,
  () => {
    console.log('colGearPieDataFilter.data: ', colGearPieDataFilter.data)

    freshPieDataFilter.value = true
  }
)
</script>
<template>
  <div class="container">
    <!-- <div class="header">
      <span>杭州国家版本馆业务数据洞察</span>
    </div> -->
    <div class="main-content">
      <!-- 征集总数 -->
      <div class="data-v-top">
        <div class="data-v-top-left">
          <img
            src="/src/assets/images/IconBagL.svg"
            alt=""
            class="img-f"
          />
          <div class="content">
            <div class="left">
              <img
                src="/src/assets/images/IconBag.svg"
                alt=""
                class="img-l"
              />
            </div>
            <div class="right">
              <div class="col-txt center">征集总数</div>
              <div class="col-count">
                <BasicCount
                  :end-val="colCount"
                  unit="件"
                  :unit-font-size="16"
                  v-if="freshPieDataAll"
                ></BasicCount>
              </div>
            </div>
          </div>
        </div>
        <div class="data-v-top-right">
          <GearPie
            :pie-data="colGearPieDataAll"
            id="colGearPieA"
          ></GearPie>
        </div>
      </div>
      <div class="data-v-main">
        <!-- 筛选条件 -->
        <div class="data-v-main-form">
          <n-form
            ref="formRef"
            inline
            :label-width="70"
            :model="formValue"
            :size="size"
            label-placement="left"
          >
            <n-form-item
              label="时间范围"
              path="dateRange"
              :label-style="{ color: '#4E5969' }"
            >
              <n-date-picker
                v-model:value="formValue.dateRange"
                type="daterange"
                clearable
                format="yyyy-MM-dd"
                @update:formatted-value="formatDate"
                style="width: 310px"
              />
            </n-form-item>
            <n-form-item
              label="征集方式"
              path="collectType"
              :label-style="{ color: '#4E5969' }"
            >
              <NSelect
                :options="collectFactionList"
                v-model:value="formValue.solicitMethodCode"
                placeholder="请选择征集方式"
                clearable
                filterable
                style="width: 160px"
              />
            </n-form-item>
            <n-form-item
              label="版本类型"
              path="itemTypeCode"
              :label-style="{ color: '#4E5969' }"
            >
              <n-tree-select
                :options="banbenList"
                children-field="childList"
                key-field="classificationCode"
                label-field="classificationName"
                v-model:value="formValue.itemTypeCode"
                :render-option="renderOption"
                placeholder="请选择版本类型"
                clearable
                filterable
                style="width: 160px"
              />
            </n-form-item>
            <n-form-item
              label="藏家"
              path="collector"
              :label-style="{ color: '#4E5969' }"
              :label-width="40"
            >
              <n-select
                v-model:value="formValue.collectorId"
                :options="collectorOptions"
                :render-option="renderOption"
                placeholder="请选择藏家"
                filterable
                clearable
                style="width: 140px"
              />
            </n-form-item>
            <n-form-item
              label="对接人"
              path="contactPeople"
              :label-style="{ color: '#4E5969' }"
              :label-width="60"
            >
              <n-input
                v-model:value="formValue.receiver"
                style="width: 140px"
                clearable
                placeholder="请输入对接人"
              />
            </n-form-item>
            <n-form-item>
              <n-button
                color="#00895B"
                round
                @click="handleValidateClick"
              >
                <template #icon>
                  <n-icon>
                    <Search />
                  </n-icon>
                </template>
                查询
              </n-button>
              <n-button
                color="#ECEEF2"
                round
                style="margin-left: 10px"
                @click="handleRestoreValidationClick"
              >
                <template #icon>
                  <n-icon color="#5a6672">
                    <Sync />
                  </n-icon>
                </template>
                <span style="color: #5a6672">重置</span>
              </n-button>
            </n-form-item>
          </n-form>
        </div>
        <!-- 条件征集总数 -->
        <div class="data-v-top">
          <div
            class="data-v-top-left"
            style="padding-right: 0"
          >
            <div
              class="content border radius"
              style="padding: 24px 48px"
            >
              <div class="left">
                <img
                  src="/src/assets/images/IconBag.svg"
                  alt=""
                  class="img-l"
                />
              </div>
              <div class="right">
                <div class="col-txt center">征集总数</div>
                <div class="col-count">
                  <BasicCount
                    :end-val="colCountFilter"
                    unit="件"
                    :unit-font-size="16"
                    v-if="freshPieDataFilter"
                  ></BasicCount>
                </div>
              </div>
            </div>
          </div>
          <div class="data-v-top-right">
            <GearPie
              :pie-data="colGearPieDataFilter"
              id="colGearPieB"
              v-if="freshPieDataFilter"
            ></GearPie>
          </div>
        </div>
        <!-- 藏家捐赠统计分析 -->
        <div class="data-v-collector">
          <n-grid
            x-gap="24"
            :cols="2"
          >
            <n-gi :span="1">
              <div class="data-v-col">
                <div class="col-title">个人藏家捐赠统计分析</div>
                <div class="col-container">
                  <div
                    class="col-item"
                    v-for="(item, index) in collectorDonatePersonal"
                    :key="index"
                  >
                    <img
                      src="/src/assets/images/IconFirst.png"
                      class="item-icon"
                      alt=""
                      v-if="index == 0"
                    />
                    <img
                      src="/src/assets/images/IconSecond.png"
                      class="item-icon"
                      alt=""
                      v-else-if="index == 1"
                    />
                    <img
                      src="/src/assets/images/IconThird.png"
                      class="item-icon"
                      alt=""
                      v-else-if="index == 2"
                    />
                    <div
                      class="item-left"
                      v-else
                    >
                      {{ index + 1 }}
                    </div>
                    <div class="item-content">
                      <div class="item-content-top">
                        <div class="item-content-name">{{ item.name }}</div>
                        <div class="item-content-count">
                          {{
                            Number(item.num) < 1000
                              ? Number(item.num)
                              : `${(Number(item.num) / 10000).toFixed(2)}万`
                          }}
                        </div>
                      </div>
                      <div class="item-content-bottom">
                        <n-progress
                          color="#326C53"
                          type="line"
                          :percentage="(Number(item.num) * 100) / colCountFilter"
                          :show-indicator="false"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </n-gi>
            <n-gi :span="1">
              <div class="data-v-col">
                <div class="col-title">单位藏家捐赠统计分析</div>
                <div class="col-container">
                  <div
                    class="col-item"
                    v-for="(item, index) in collectorDonateEnterprise"
                    :key="index"
                  >
                    <img
                      src="/src/assets/images/IconFirst.png"
                      class="item-icon"
                      alt=""
                      v-if="index == 0"
                    />
                    <img
                      src="/src/assets/images/IconSecond.png"
                      class="item-icon"
                      alt=""
                      v-else-if="index == 1"
                    />
                    <img
                      src="/src/assets/images/IconThird.png"
                      class="item-icon"
                      alt=""
                      v-else-if="index == 2"
                    />
                    <div
                      class="item-left"
                      v-else
                    >
                      {{ index + 1 }}
                    </div>
                    <div class="item-content">
                      <div class="item-content-top">
                        <div class="item-content-name">{{ item.name }}</div>
                        <div class="item-content-count">
                          {{
                            Number(item.num) < 1000
                              ? Number(item.num)
                              : `${(Number(item.num) / 10000).toFixed(2)}万`
                          }}
                        </div>
                      </div>
                      <div class="item-content-bottom">
                        <n-progress
                          color="#326C53"
                          type="line"
                          :percentage="(Number(item.num) * 100) / colCountFilter"
                          :show-indicator="false"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </n-gi>
          </n-grid>
        </div>
        <!-- 征集品类型分析 -->
        <div class="data-v-collector">
          <n-grid
            x-gap="24"
            :cols="5"
          >
            <n-gi :span="2">
              <div class="data-v-col">
                <div class="col-title">征集品一级类型分析</div>
                <n-spin :show="!showFirst">
                  <div
                    class="col-container"
                    style="height: 320px"
                  >
                    <GearPieL
                      :pie-data="collectCategory"
                      id="colGearPieFirst"
                      v-if="showFirst"
                      @fresh="onChangeSecondCategory"
                    ></GearPieL>
                  </div>
                </n-spin>
              </div>
            </n-gi>
            <n-gi :span="3">
              <div class="data-v-col">
                <div class="col-title">征集品二级类型分析</div>
                <n-spin :show="!showSecond">
                  <div
                    class="col-container"
                    style="display: flex; justify-content: space-between; height: 320px"
                  >
                    <template v-if="showSecond">
                      <GearPieL
                        :pie-data="collectSecondCategory"
                        :show-legend="false"
                        id="colGearPie"
                      ></GearPieL>
                      <div class="colSecTop">
                        <n-grid
                          x-gap="24"
                          :cols="2"
                        >
                          <n-gi :span="1">
                            <div
                              class="colSecTopItem"
                              v-for="(item, index) in collectGategoryTopL"
                              :key="index"
                            >
                              <div class="item-num">
                                {{ index + 1 }}
                              </div>
                              <n-ellipsis style="width: 120px; max-width: 120px">
                                {{ item.category }}
                              </n-ellipsis>
                              <n-progress
                                color="#326C53"
                                type="line"
                                :percentage="(Number(item.num) * 100) / colCountFilter"
                                :show-indicator="false"
                              />
                              <div class="item-count">
                                {{
                                  Number(item.num) < 1000
                                    ? Number(item.num)
                                    : `${(Number(item.num) / 10000).toFixed(2)}万`
                                }}
                              </div>
                            </div>
                          </n-gi>
                          <n-gi :span="1">
                            <div
                              class="colSecTopItem"
                              v-for="(item, index) in collectGategoryTopR"
                              :key="index"
                            >
                              <div class="item-num">
                                {{ index + 11 }}
                              </div>

                              <n-ellipsis style="width: 120px; max-width: 120px">
                                {{ item.category }}
                              </n-ellipsis>
                              <n-progress
                                color="#326C53"
                                type="line"
                                :percentage="(Number(item.num) * 100) / colCountFilter"
                                :show-indicator="false"
                              />
                              <div class="item-count">
                                {{
                                  Number(item.num) < 1000
                                    ? Number(item.num)
                                    : `${(Number(item.num) / 10000).toFixed(2)}万`
                                }}
                              </div>
                            </div>
                          </n-gi>
                        </n-grid>
                      </div>
                    </template>
                  </div>
                </n-spin>
              </div>
            </n-gi>
          </n-grid>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  background-color: #f6f7f9;
  .header {
    font-family: 'HYCuSongJ';
    font-size: 24px;
    line-height: 56px;
    color: #ffffff;
    font-weight: 700;
    background-color: #326c53;
    span {
      margin-left: 24px;
    }
  }
  .main-content {
    // min-width: 1670px;
    padding: 24px;
    // 征集总数
    .data-v-top {
      display: flex;
      .data-v-top-left {
        // width: 36vw;
        padding: 44px;
        border-radius: 8px;
        background-color: #ffffff;
        display: flex;
        position: relative;
        overflow: hidden;
        .img-f {
          /* Vector */
          position: absolute;
          right: 0;
          top: -10px;
          opacity: 0.1;
        }
        .content {
          padding: 24px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .left {
            width: 32px;
            height: 32px;
            padding: 32px;
            border-radius: 50%;
            background-color: #d7f1de;
            display: flex;
            justify-content: center;
            align-items: center;
            .img-l {
              width: 32px;
              height: 32px;
            }
          }
          .right {
            width: 360px;
            display: flex;
            justify-content: space-between;
            margin-left: 16px;
            .col-txt {
              font-size: 16px;
            }
            .col-count {
              font-size: 40px;
              color: #00895b;
            }
          }
        }
      }
      .data-v-top-right {
        margin-left: 24px;
        border-radius: 8px;
        display: flex;
        justify-content: center;
        flex-grow: 1;
        background-color: #ffffff;
      }
    }
    // 数据分析主容器
    .data-v-main {
      margin-top: 24px;
      background-color: #ffffff;
      // 筛选条件
      .data-v-main-form {
        padding: 24px 10px;
        margin: 0 auto;
      }
      // 藏家捐赠统计分析
      .data-v-collector {
        display: flex;
        padding: 24px;
        .data-v-col {
          .col-title {
            font-size: 16px;
            line-height: 48px;
            padding: 0 24px;
            border-bottom: 1px solid #f1f2f4;
          }
          .col-container {
            .col-item {
              display: flex;
              align-items: center;
              padding: 6px 16px;
              .item-icon {
                width: 32px;
                height: 32px;
              }
              .item-left {
                width: 32px;
                height: 32px;
                line-height: 32px;
                font-size: 18px;
                color: #86909c;
                display: flex;
                align-items: center;
                justify-content: center;
              }
              .item-content {
                margin-left: 8px;
                flex-grow: 1;
                .item-content-top {
                  display: flex;
                  justify-content: space-between;
                  margin-bottom: 5px;
                  .item-content-name {
                  }
                  .item-content-count {
                    color: #326c53;
                    font-size: 16px;
                  }
                }
              }
            }
          }
          .colSecTop {
            flex-grow: 1;
            .colSecTopItem {
              display: flex;
              align-items: center;
              font-size: 12px;
              margin-top: 8px;
              .item-num {
                align-items: center;
                color: #86909c;
                display: flex;
                justify-content: center;
                line-height: 24px;
                width: 24px;
                margin-right: 5px;
              }
              .item-count {
                width: 100px;
                text-align: right;
                color: #326c53;
              }
            }
          }
        }
      }
    }
  }
}
.border {
  border: 1px solid #e2e5e9;
}
.radius {
  border-radius: 8px;
}
:deep(.n-form.n-form--inline) {
  justify-content: center;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
